最近要試著做有動畫的按鈕,當hover的時候會有一個icon刷新的感覺,可以看Demo。
先認識:before :after
每個class都有:before :after這兩個偽元素,你可以想像成創造了一個class=”btn”後會變成:1
2
3.btn {}
.btn:before {}
.btn:after{}
不管css寫在哪都會有效果,值得注意的是:before和:after一定要有content這個屬性才有效果
,而content是內文的意思,像是innerHtml
。
下列是同等效果:
正常元素1
2
3
4<style>
.btn { color: red; };
</style>
<div class="btn">Btn</div>
偽元素1
2
3
4
5
6
7<style>
.btn:before {
content: 'Btn';
color: red;
};
</style>
<div class="btn"></div>
接下來進入主題
先做出有icon的原生還沒有動畫的buttom
1 | <div class="btn"> |
1 | .btn {//btn的容器 |
接下來要注意的是transition(動畫)設定在初始的class裡面
,所以我們更新後把CSS更新如下(記得我們還沒創造動畫唷!):1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52.btn {
text-align: center;
width: 100px;
height: 30px;
margin: 1em;
padding: 0px 10px 0px;
border: 1px solid;
border-radius: 20px;
cursor: pointer;
}
.btn .icon {//會動所以加上動畫屬性
margin: 0px;
padding: 0px;
display: inline-block;
position: relative;
right: 14px;
height: 29px;
width: 29px;
border: 1px solid;
border-radius: 999px;
background-color: #fff;
z-index: 999;
-webkit-transition: 0.6s;
-moz-transition: 0.6s;
-o-transition: 0.6s;
transition: 0.6s;
}
.btn span {//會動(要消失)所以加上動畫屬性
opacity: 1;
position: relative;
bottom: 10px;
right: 10px;
-webkit-transition: 0.6s;
-moz-transition: 0.6s;
-o-transition: 0.6s;
transition: 0.6s;
}
.btn:after {//會動(要出現)所以加上動畫屬性
content: 'Go now';
opacity: 0;
display: inline-block;
position: relative;
bottom: 32px;
right: 10px;
-webkit-transition: 0.6s;
-moz-transition: 0.6s;
-o-transition: 0.6s;
transition: 0.6s;
}
最後我們觸發動畫是利用hover
,所以把動畫的結果寫出來,css更新如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64.btn {
text-align: center;
width: 100px;
height: 30px;
margin: 1em;
padding: 0px 10px 0px;
border: 1px solid;
border-radius: 20px;
cursor: pointer;
}
.btn .icon {
margin: 0px;
padding: 0px;
display: inline-block;
position: relative;
right: 14px;
height: 29px;
width: 29px;
border: 1px solid;
border-radius: 999px;
background-color: #fff;
z-index: 999;
-webkit-transition: 0.6s;
-moz-transition: 0.6s;
-o-transition: 0.6s;
transition: 0.6s;
}
.btn:hover .icon {//讓icon向右邊跑
right: -77px;
}
.btn span {
opacity: 1;
position: relative;
bottom: 10px;
right: 10px;
-webkit-transition: 0.6s;
-moz-transition: 0.6s;
-o-transition: 0.6s;
transition: 0.6s;
}
.btn:hover span {//讓初始內文消失
opacity: 0;
}
.btn:after {
content: 'Go now';
opacity: 0;
display: inline-block;
position: relative;
bottom: 32px;
right: 10px;
-webkit-transition: 0.6s;
-moz-transition: 0.6s;
-o-transition: 0.6s;
transition: 0.6s;
}
.btn:hover::after {//讓更新內文出現
opacity: 1;
}
這樣就大功告成囉!!!!